package com.airnewslinkosky.ticket.ui.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.adapter.MySimpleAdapter;
import com.airnewslinkosky.ticket.model.CustomerInfo;
import com.airnewslinkosky.ticket.model.CustomerInfoResult;
import com.airnewslinkosky.ticket.model.PassengerInfo;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.pay.util.BaseHelper;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.util.Constants;
import com.mobclick.android.MobclickAgent;
/**
 * 机构客户管理列表查询
 * @author toshiba
 *
 */
public class ClientList  extends BaseActivity implements OnClickListener,OnItemClickListener{

	public ClientAdapter sa;
	public ListView lv;
	
	public static List<CustomerInfo> customerInfos = new ArrayList<CustomerInfo>();
	private List<Map<String,Object>> clientsList = new ArrayList<Map<String,Object>>();
	
	private Button buttonUpdateContact,buttonDeleteContact;
	private int editCount = 0;
	private List<String> positionSelect = new ArrayList<String>();//选定的
	
	public static boolean isSearch = false;
	public static boolean isShowSearch = true;
	private boolean isDelete = false;
	
	public final int NORESULT = 3;
	public final int NOORDER = 4;
	public final int NOORDERSTAT = 5;
	public final int NET_ERROR=6;
	public final int SEARCH_ERROR=7;
	public final int SEARCH_SUCCESS=8;
	public final int DELETE_SUCCESS = 9;
	
	private ProgressDialog progressDialog = null;
	public Handler myHandler;
	private Toast toast;
	private SharedPreferences sp;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client_list);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
        
		activityList.add(this);
		
		findViewById(R.id.backBut).setOnClickListener(this);
		
		buttonUpdateContact = (Button) findViewById(R.id.button_update_contact);
		buttonUpdateContact.setOnClickListener(this);
		
		buttonDeleteContact = (Button) findViewById(R.id.button_delete_contact);
		buttonDeleteContact.setOnClickListener(this);
		
		lv = (ListView) findViewById(R.id.clientlist);
		lv.setOnItemClickListener(this);
		
		if(isSearch){
			search();
		} else {
			initData();
		}
		
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case NORESULT:
					toast = Toast.makeText(ClientList.this, "未找到符合条件的机构客户", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case NOORDER:
					toast = Toast.makeText(ClientList.this, "无机构客户信息", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case NET_ERROR:
					toast = Toast.makeText(ClientList.this, "网络超时，连接失败", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case SEARCH_ERROR:
					toast = Toast.makeText(ClientList.this,  (String)msg.obj, Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case SEARCH_SUCCESS:
					initData();
					break;
				case DELETE_SUCCESS:
					initData();
					break;
				}
				super.handleMessage(msg);
			}
		};
	}
	
	private void initData() {
		clientsList = new ArrayList<Map<String,Object>>();
		for(CustomerInfo customerInfo : customerInfos){
			Map<String, Object> map = new HashMap<String, Object>();
			System.out.println("customerName="+customerInfo.CustomerName);
			map.put("customerNo", customerInfo.CustomerNo);
			map.put("customerName",customerInfo.CustomerName);
			map.put("principal", "负:" + customerInfo.Principal);
			map.put("salesRepresent", "销:" + customerInfo.SalesRepresent);
			map.put("mobile", "负:" + (customerInfo.Mobile == null ? customerInfo.Telephone : customerInfo.Mobile));
			map.put("customerInfo", customerInfo);
			clientsList.add(map);
		}
		
		sa = new ClientAdapter(
				this,
				clientsList,
				R.layout.client_row,
				new String[] { "customerNo", "customerName","principal","salesRepresent","mobile"},
				new int[] { R.id.customerNo, R.id.customerName,R.id.principal,R.id.salesRepresent,R.id.mobile}); 
		lv.setAdapter(sa);
		sa.notifyDataSetChanged();
		
	}
	
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.backBut: 
				Intent intentR = new Intent();
				intentR.setClass(ClientList.this, ClientSearch.class);
				startActivity(intentR);
				break;
			case R.id.button_delete_contact:
				delete();
				break;	
			case R.id.button_update_contact:
				editCount++;
				initData();
				break;
		}
	}
	
	
	private void delete() {
		if(positionSelect.size() == 0){
			BaseHelper.showDialog(ClientList.this, "提示", "请点击编辑后选择删除的机构客户",R.drawable.infoicon);
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);    
			builder.setTitle("删除机构客户");    
			builder.setMessage("真的要删除这些记录吗？");    
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {    
			public void onClick(DialogInterface dialog, int which) {   
				    deteleAction();
				    isShowSearch = false;
				}
			});    
			   
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {    
			public void onClick(DialogInterface dialog, int which) {    
			dialog.cancel();    
			}    
			});    
			   
			AlertDialog ad = builder.create();    
			ad.show(); 
			
			
		}
	}
	
	
	private void deteleAction() {
		progressDialog = ProgressDialog.show(ClientList.this, "请稍等...", "正在删除机构客户中...",true);
		final Thread thread1 = new Thread() {
			public void run() {
//				sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
//		        String userIdLogin = sp.getString("userIdB2B", null);
//		        String userPwd =  sp.getString("userPwdB2B", null);
//		        String asToken =   sp.getString("ASTokenB2B", null);
		        String userIdLogin = Constants.USERID;
		        String userPwd =  Constants.USERPWD;
		        String asToken =  Constants.ASToken;
		        CustomerInfoResult customerInfoResult = null;
		        
		        if(positionSelect.size()!=0){
			        for(String pNo:positionSelect){
			        	customerInfoResult = WebAccessor.searchCustomerInfoManage(ClientList.this,userIdLogin,userPwd,asToken,"DELETEGROUP","",pNo,"");
			        	//删除列表容器中的该列
			        	System.out.println("begin customerInfos size = " + customerInfos.size());
			        	for(CustomerInfo customerInfo : customerInfos){
			        		if(customerInfo.CustomerNo.equals(pNo)){
			        			customerInfos.remove(customerInfo);
			        			System.out.println("after customerInfos size = " + customerInfos.size());
			        		}
			        	}
			        }
		        }
		        if("0".equals(customerInfoResult.Result)){
					Message msg = new Message();
					msg.what = DELETE_SUCCESS;
					myHandler.sendMessage(msg);
		        } else {
		        	Message msg = new Message();
					msg.what = SEARCH_ERROR;
					msg.obj = customerInfoResult.ErrorDescription;
					myHandler.sendMessage(msg);
		        }
		        
				progressDialog.dismiss();
			}
		};
		
		progressDialog.setCancelable(true);
		thread1.start();
	}
	
	public void onItemClick(AdapterView<?> arg0, View v, int position,
			long arg3) {
		Map<String, Object> item = (Map<String, Object>) lv.getAdapter().getItem(position);
		CustomerInfo customerInfo = (CustomerInfo)item.get("customerInfo");
		Intent intent = new Intent();
		ClientAdd.customerInfo = customerInfo;
		intent.setClass(this, ClientAdd.class);
		startActivity(intent);
	}
	
	
	private void search() {
		if(isShowSearch){
			progressDialog = ProgressDialog.show(this, "请稍等...", "查询机构客户中...",true);
		}
		final Thread thread1 = new Thread() {
			public void run() {
//				sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
//		        String userIdLogin = sp.getString("userIdB2B", null);
//		        String userPwd =  sp.getString("userPwdB2B", null);
//		        String asToken =   sp.getString("ASTokenB2B", null);
		        
		        String userIdLogin = Constants.USERID;
		        String userPwd =  Constants.USERPWD;
		        String asToken =  Constants.ASToken;
		        
				String operateType = "";
			    String userName = "";
			    String mobile = "";
			    CustomerInfoResult customerInfoResult = null;
			    try{
			        customerInfoResult = WebAccessor.searchCustomerInfoManage(ClientList.this,userIdLogin,userPwd,asToken,operateType,userName,"",mobile);
					
			        if(progressDialog.isShowing()){
						progressDialog.dismiss();
					}
			        if("0".equals(customerInfoResult.Result)){
			        	customerInfos = customerInfoResult.customerInfoList;
						Message msg = new Message();
						msg.what = SEARCH_SUCCESS;
						myHandler.sendMessage(msg);
			        } else {
			        	Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = customerInfoResult.ErrorDescription;
						myHandler.sendMessage(msg);
			        }
			    } catch(Exception e) {
			    	Message msg = new Message();
					msg.what = NET_ERROR;
					myHandler.sendMessage(msg);
			    }
			}
		};
		thread1.start();
	}
	
	
	private class ClientAdapter extends MySimpleAdapter {
		private List<Map<String, Object>> list;
		public ClientAdapter(Context context, List<Map<String, Object>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			list = data;
		}
  		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final View v = super.getView(position, convertView, parent);
			final TextView contactText =  (TextView) v.findViewById(R.id.contactText);
			final CustomerInfo customerInfo = (CustomerInfo) list.get(position).get("customerInfo");
			
			contactText.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intentS = new Intent();
					intentS.setClass(ClientList.this, ClientContactsList.class);
					ClientContactsList.customerInfo = customerInfo;
					ClientContactsList.customerNo = customerInfo.CustomerNo;
					ClientContactsList.isSearch = true;
					startActivity(intentS);
				}
				
			});
			
			final CheckBox checkPassenger = (CheckBox) v.findViewById(R.id.checkPassenger);
			checkPassenger.setClickable(true);
			if(editCount%2==1){
				checkPassenger.setVisibility(View.VISIBLE);
			} else {
				checkPassenger.setVisibility(View.GONE);
			}
			TextView customerNoView = (TextView) v.findViewById(R.id.customerNo);
			final String number  = customerNoView.getText().toString();
			positionSelect.clear();
			checkPassenger.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(checkPassenger.isChecked()){
						System.out.println("点击了"+number);
						positionSelect.add(number);
					}else {
						positionSelect.remove(number);//存放的是号码的值
					}
				}
			});
			return v;
		}
  	}
	
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  

}
